package system

import (
	"errors"
	"mime/multipart"
	"strings"
	"time"

	"gorm.io/gorm"
	"main.go/global"
	"main.go/model/system"
	systemReq "main.go/model/system/request"
	"main.go/utils"
	"main.go/utils/upload"
)

type UploadFileService struct{}

func (s *UploadFileService) UploadFile(header *multipart.FileHeader, ossType string) (file *system.SysFileUploadFile, err error) {
	oss := upload.NewOss(ossType)
	filePath, key, uploadErr := oss.UploadFile(header)
	if uploadErr != nil {
		return nil, uploadErr
	}
	name := strings.Split(header.Filename, ".")
	data := &system.SysFileUploadFile{
		Url:     filePath,
		Name:    header.Filename,
		Tag:     name[len(name)-1],
		Key:     key,
		OssType: ossType,
	}
	err = global.EVA_DB.Create(&data).Error
	return data, err
}

func (s *UploadFileService) Delete(id int) (err error) {
	var file *system.SysFileUploadFile
	err = global.EVA_DB.Where("id = ?", id).First(&file).Error
	if err != nil {
		return err
	}
	oss := upload.NewOss(file.OssType)
	if err = oss.DeleteFile(file.Key); err != nil {
		return errors.New("文件删除失败")
	}
	// 事务
	return global.EVA_DB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Where("id = ?", id).Unscoped().Delete(&system.SysFileUploadFile{}).Error; err != nil {
			return err
		}
		return nil
	})
}

func (s *UploadFileService) Update(req *system.SysFileUploadFile) (out *system.SysFileUploadFile, err error) {
	updateData := make(map[string]interface{})
	if len(req.Name) > 0 {
		updateData["name"] = req.Name
	}

	err = global.EVA_DB.Model(&system.SysFileUploadFile{}).Where(system.SysFileUploadFile{
		EVA_MODEL: global.EVA_MODEL{
			ID: req.ID,
		},
	}).Updates(updateData).Error
	return out, err
}

func (s *UploadFileService) List(req *systemReq.SysFileUploadFileListReq) (list []*system.SysFileUploadFile, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Page - 1)
	db := global.EVA_DB.Model(&system.SysFileUploadFile{})
	// 如果有条件搜索 下方会自动创建搜索语句
	if len(req.Name) != 0 {
		db = db.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.StartCreatedAt != 0 && req.EndCreatedAt != 0 {
		t1 := time.Unix(req.StartCreatedAt, 0).In(utils.ShLocation)
		t2 := time.Unix(req.EndCreatedAt, 0).In(utils.ShLocation)
		db = db.Where("created_at BETWEEN ? AND ?", t1, t2)
	}
	err = db.Count(&total).Error
	if err != nil {
		return list, total, err
	}

	err = db.Order("id desc").Limit(limit).Offset(offset).Find(&list).Error
	return list, total, err
}
